//
//  RegisterFormCell.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/9.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

enum RegisterFormCellType: Int {
    case name
    case idCard
    case area
    case address
    case phone
    case code
    case password
    case repassword
    case register
    
    var placeholder: String {
        switch self {
        case .name: return "请输入姓名"
        case .idCard: return "请输入身份证号码"
        case .area: return "请选择省市区"
        case .address: return "请输入详细地址"
        case .phone: return "请输入手机号"
        case .code: return "请输入验证码"
        case .password: return "请输入密码"
        case .repassword: return "请确认密码"
        default: return ""
        }
    }
}

protocol RegisterFormCellDelegate: NSObjectProtocol {
    func register(_ cell: RegisterFormCell, didEndEditing model: RegisterModel)
    func register(didStartRegister cell: RegisterFormCell)
    func register(didSendSmsCode cell: RegisterFormCell)
}

class RegisterFormCell: UITableViewCell {

    static let reuseIdentifier = "registerFormCellId"
    
    weak var delegate: RegisterFormCellDelegate?
    
    var cellType: RegisterFormCellType = .name {
        didSet {
            initUI(with: cellType)
        }
    }
    
    private var model = RegisterModel()
    
    func configure(with model: RegisterModel,
                   cellType: RegisterFormCellType,
                   type: YSGLoginSubViewType = .register)
    {
        self.model = model
        self.cellType = cellType
        textfield.placeholder = cellType.placeholder
        
        switch type {
        case .register:
            let row = model.isCheck ? (cellType.rawValue > 0 ? cellType.rawValue - 3 : cellType.rawValue) : cellType.rawValue
            
            titleImageView.image = UIImage(named: model.titles[row])
        case .forget:
            let row = cellType.rawValue - 4
            titleImageView.image = UIImage(named: model.titles[row])
        }
        
        switch cellType {
        case .register:
            registerBtn.isEnabled = true
            registerBtn.setTitle(type.description, for: .normal)
        case .code:
            textfield.text = model.code
            sendCodeBtn.isEnabled = model.codeBtnEnable && !sendCodeBtn.isTimer
        case .name:
            textfield.text = model.name
        case .idCard:
            textfield.text = model.idCard
        case .area:
            textfield.text = model.area
        case .address:
            textfield.text = model.address
        case .phone:
            textfield.text = model.phone
        case .password:
            textfield.text = model.password
        case .repassword:
            textfield.text = model.repassword
        }
    }
    
    func resetCodeBtn() {
        sendCodeBtn.reset()
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var titleImageView: UIImageView = {
        let imageView = UIImageView()
        return imageView
    }()
    
    private lazy var textfield: UITextField = {
        let view = UITextField()
        view.font = UIFont.regular(14)
        view.textColor = UIColor.textDark
        view.tintColor = UIColor.textDark
        view.delegate = self
        
        let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 44))
        view.leftView = leftView
        view.leftViewMode = .always
        
        return view
    }()
    
    private lazy var splitLine: UIView = {
        let view = UIView()
        view.backgroundColor = .splLineNormal
        return view
    }()
    
    private lazy var sendCodeBtn: CountDownButton = {
        let button = CountDownButton(type: .custom)
        button.isEnabled = false
        button.addTarget(self, action: #selector(sendCode(_:)), for: .touchUpInside)
        return button
    }()
    
    private lazy var registerBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("注 册", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.medium(16)
        button.setBackgroundImage(UIImage(color: .mainGray), for: .disabled)
        button.setBackgroundImage(UIImage(color: .mainColor), for: .normal)
        button.setBackgroundImage(UIImage(color: .mainGray), for: .highlighted)
        button.addTarget(self, action: #selector(register(_:)), for: .touchUpInside)
        return button
    }()

}

// MARK: - 事件监听
extension RegisterFormCell {
    @objc private func register(_ sender: UIButton) {
        delegate?.register(didStartRegister: self)
    }
    
    @objc private func sendCode(_ sender: CountDownButton) {
        sender.countDown(with: 60)
        delegate?.register(didSendSmsCode: self)
    }
}

extension RegisterFormCell {
    private func initUI(with cellType: RegisterFormCellType) {
      //  removeAllSubviews()
        switch cellType {
        case .name,
             .idCard,
             .address:
            setupUILayout()
        case .phone:
            setupUILayout()
            textfield.keyboardType = .phonePad
        case .area:
            setupUILayout()
            textfield.isEnabled = false
        case .code:
            setupCodeUILayout()
            textfield.keyboardType = .numberPad
        case .password, .repassword:
            setupUILayout()
            textfield.isSecureTextEntry = true
        case .register:
            setupRegisterBtn()
        }
    }
    
    private func removeAllSubviews() {
        titleImageView.removeFromSuperview()
        textfield.removeFromSuperview()
        splitLine.removeFromSuperview()
        sendCodeBtn.removeFromSuperview()
        registerBtn.removeFromSuperview()
    }
    
    private func setupUILayout() {


        contentView.addSubview(titleImageView)
        contentView.addSubview(textfield)
        contentView.addSubview(splitLine)
        
        contentView.backgroundColor = .clear
        titleImageView.backgroundColor = .clear
        textfield.backgroundColor = .clear
        self.backgroundColor = .clear
        
        titleImageView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.centerY.equalToSuperview()
            make.width.equalTo(24)
            make.height.equalTo(24)
        }
        
        textfield.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(titleImageView.snp.right).offset(8)
            make.right.equalTo(-15)
            make.height.equalTo(36)
        }
        
        splitLine.snp.makeConstraints { (make) in
            make.height.equalTo(0.5)
            make.left.equalTo(16)
            make.right.bottom.equalToSuperview()
        }
    }
    
    private func setupCodeUILayout() {
        contentView.addSubview(titleImageView)
        contentView.addSubview(textfield)
        contentView.addSubview(splitLine)
        contentView.addSubview(sendCodeBtn)
        
        
        contentView.backgroundColor = .clear
        titleImageView.backgroundColor = .clear
        textfield.backgroundColor = .clear
        self.backgroundColor = .clear
        
        titleImageView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.centerY.equalToSuperview()
            make.width.equalTo(24)
            make.height.equalTo(24)
        }
        
        textfield.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(titleImageView.snp.right).offset(8)
            make.right.equalTo(sendCodeBtn.snp.left)
            make.height.equalTo(36)
        }
        
        sendCodeBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(textfield.snp.right)
            make.right.equalTo(-15)
            make.size.equalTo(CGSize(width: 100, height: 30))
        }
        
        splitLine.snp.makeConstraints { (make) in
            make.height.equalTo(0.5)
            make.left.equalTo(16)
            make.right.bottom.equalToSuperview()
        }
    }
    
    private func setupRegisterBtn() {
        registerBtn.layer.cornerRadius = 25
        registerBtn.layer.masksToBounds = true
        contentView.addSubview(registerBtn)
        registerBtn.snp.makeConstraints { (make) in
            make.left.equalTo(32)
            make.right.equalTo(-32)
            make.height.equalTo(50)
            make.bottom.equalTo(-5)
        }
    }
}

extension RegisterFormCell: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        splitLine.backgroundColor = .splLineSelect
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        splitLine.backgroundColor = .splLineNormal
        
        switch cellType {
        case .name: model.name = textField.text!
        case .idCard: model.idCard = textField.text!
        case .phone: model.phone = textField.text!
        case .code: model.code = textField.text!
        case .password: model.password = textField.text!
        case .repassword: model.repassword = textField.text!
        case .address: model.address = textField.text!
        default: break
        }
        
        delegate?.register(self, didEndEditing: model)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if cellType == .idCard {
            let totalLength = (textField.text?.lengthOfBytes(using: .utf8))! - range.length + string.lengthOfBytes(using: .utf8)
            if totalLength > 18 { return false }
            let lengthOfStr = string.lengthOfBytes(using: .utf8)
            for index in 0..<lengthOfStr {
                let chara = (string as NSString).character(at: index)
                // 48-57;{0,9};65-90;{A..Z};97-122:{a..z}
                if chara < 48 { return false }
                if totalLength < 18 && chara > 57 {
                    return false
                }
                if totalLength == 18 &&
                    ((chara > 57 && chara < 65) || (chara > 90 && chara < 97) || chara > 122) {
                    return false
                }
            }
            return true
        } else if cellType == .phone {
            let totalLength = (textField.text?.lengthOfBytes(using: .utf8))! - range.length + string.lengthOfBytes(using: .utf8)
            if totalLength > 11 { return false }
            let lengthOfStr = string.lengthOfBytes(using: .utf8)
            for index in 0..<lengthOfStr {
                let chara = (string as NSString).character(at: index)
                // 48-57;{0,9};65-90;{A..Z};97-122:{a..z}
                if chara < 48 || chara > 57 { return false }
            }
            return true
        }
        return true
    }
}
